﻿using System;
using System. Linq;
using System. Net;
using System. Windows;
using System. Windows. Data;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using Microsoft. Phone. Tasks;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using WP7_ControlsLib. Controls;
using NextApp. WP7. Util;
using System. Text. RegularExpressions;
using NextApp. WP7. Cache. NextApp;
using System. Windows. Controls;

namespace NextApp. WP7. View
{
    public partial class PostDetail : PhoneApplicationPage
    {
        #region Initialize
        public PostDetail( )
        {
            InitializeComponent( );
			this. PrepareToOrientation( );
            this. pivot. Title = Config. Instance. blog_title;
            this. Loaded += new RoutedEventHandler(PostDetail_Loaded);
            EventSingleton. Instance. OnRefreshComments += (s, e) =>
                {
                    if ( (s as Controls.CommentList) == this.comments)
                    {
                        if ( this.postID != 0 )
                        {
                            this. comments. Reload(true, this. postID, 0, true);
                        }
                    }
                };
			this. comments. GetTemplate(false);
        }
        private int postID { get; set; }
        private Post post { get; set; }
        protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs e)
        {
            //登入注销处理
            Util. Tool. CheckAppBar(this);
            //处理PostID
            this. Receive_PostID( );
            //处理Portal
            this. Receive_Portal( );

            base. OnNavigatedTo(e);
        }
        public void Reload( )
        {
			//如果数据能够从缓存中获取
			if ( GetDataFromCache( ) )
			{
 				//同时进行入队操作
				CacheNextApp. Instance. Enqueue(new AsyncMissionNextApp
				{
					queryStringWithUrl = Config. Instance. GetApi(string. Format("{0}&post={1}&guid={2}", NextAppSingleton. Instance. url_post_detail, postID, Guid. NewGuid( ))),
					 Type = AsyncMissionNextAppType.Post_Detail,
				});
			}
			else
			{
				//如果没能从缓存中获取数据 则立即前台获取
				WebClient client = new WebClient( );
				client. Headers[ "User-Agent" ] = Config. Instance. Http_User_Agent;
				client. DownloadStringCompleted += (s, e1) =>
				{
					if ( e1. Error != null )
					{
						MessageBox. Show("获取文章详情发生错误", "网络错误", MessageBoxButton. OK);
						return;
					}
					XElement postElement;
					try
					{
						postElement = XElement. Parse(e1. Result). Element("post");
					}
					catch ( Exception )
					{
						return;
					}
					Post post = new Post
					{
						id = postElement. Element("id"). Value. ToInt32( ),
						catalog = postElement. Element("catalog"). Value. Split(',') != null ? postElement. Element("catalog"). Value. Split(','). Select(c => c. ToInt32( )). ToArray( ) : null,
						title = postElement. Element("title"). Value,
						url = postElement. Element("url"). Value,
						body = postElement. Element("body"). Value,
						tags = postElement. Element("tags"). Value. Split(','),
						author = postElement. Element("author"). Value,
						pubDate = postElement. Element("pubDate"). Value,
						commentCount = postElement. Element("commentCount"). Value. ToInt32( ),
						relativePosts = postElement. Element("relativePosts") == null ?
												null :
												postElement. Element("relativePosts"). Elements("relativePost"). Select(
												r => new RelativePost
												{
													id = r. Element("id"). Value. ToInt32( ),
													author = r. Element("author"). Value,
													pubDate = r. Element("pubDate"). Value,
													title = r. Element("title"). Value,
												}
											). ToArray( ),
						//上一篇 下一篇文章ID 的获取
						previous = postElement. Element("previous") == null ? 0 : postElement. Element("previous"). Value. ToInt32( ),
						next = postElement. Element("next") == null ? 0 : postElement. Element("next"). Value. ToInt32( ),
					};
					//测试获取整篇详细文章成功               
					DataSingleton. Instance. postToShare = post;
					this. DisplayCommentCount(post. commentCount);
					//存储到缓存中
					CacheNextApp. Instance. SavePostDetailToCache(post);
					//入队操作 上一篇/下一篇的 入队操作
					if ( post. next > 0 )
					{
						CacheNextApp. Instance. Enqueue(new AsyncMissionNextApp
						{
							queryStringWithUrl = Config. Instance. GetApi(string. Format("{0}&post={1}&guid={2}", NextAppSingleton. Instance. url_post_detail, post. next, Guid. NewGuid( ))),
							Type = AsyncMissionNextAppType. Post_Detail,
						});
					}
					if ( post.previous > 0 )
					{
						CacheNextApp. Instance. Enqueue(new AsyncMissionNextApp
						{
							queryStringWithUrl = Config. Instance. GetApi(string. Format("{0}&post={1}&guid={2}", NextAppSingleton. Instance. url_post_detail, post. previous, Guid. NewGuid( ))),
							Type = AsyncMissionNextAppType. Post_Detail,
						});
					}
					
					//显示
					this. Grid_Post. Visibility = System. Windows. Visibility. Visible;
					this. post = post;
					this. ProgressIndicatorIsVisible = false;
					this. Grid_Post. DataContext = post;
					string bodyResult;
					try
					{
						bodyResult = Util. Tool. ProcessHTMLString(post. body);
					}
					catch
					{
						bodyResult = post. body;
					}
					//这里要进行 HTML 中文转码
					bodyResult = ControlHelper. ConvertExtendedASCII(bodyResult);
					this. browser. NavigateToString(bodyResult);
					//分配相关文章到第3个 Tab
					this. relativePosts. SetDatas(post. relativePosts);
				};
				//异步获取文章详情
				if ( NextAppSingleton. Instance. url_post_detail. IsNotNullOrWhitespace( ) )
				{
					client. DownloadStringAsync(new Uri(Config. Instance. GetApi(string. Format("{0}&post={1}&guid={2}", NextAppSingleton. Instance. url_post_detail, postID, Guid. NewGuid( ))), UriKind. Absolute));
					this. ProgressIndicatorIsVisible = true;
				}
			}
        }

		private bool GetDataFromCache( )
		{
			Post postCache = CacheNextApp. Instance. GetPostDetailFromCache(postID);
			if ( postCache != null )
			{
				DataSingleton. Instance. postToShare = postCache;
				this. Grid_Post. Visibility = System. Windows. Visibility. Visible;
				this. post = postCache;
				this. ProgressIndicatorIsVisible = false;
				this. Grid_Post. DataContext = postCache;
				this. DisplayCommentCount(postCache. commentCount);
				string bodyResult;
				try
				{
					bodyResult = Util. Tool. ProcessHTMLString(postCache. body);
				}
				catch
				{
					bodyResult = postCache. body;
				}
				//这里要进行 HTML 中文转码
				bodyResult = ControlHelper. ConvertExtendedASCII(bodyResult);
				this. browser. NavigateToString(bodyResult);
				//分配相关文章到第3个 Tab
				this. relativePosts. SetDatas(postCache. relativePosts);
				return true;
			}
			else
			{
				return false;
			}
		}
        #endregion

        #region 回到上一页
        private void icon_GoBack_Click(object sender, EventArgs e)
        {
            if ( this. NavigationService. CanGoBack )
            {
                this. NavigationService. GoBack( );
            }
            else
            {
                this. NavigationService. Navigate(new Uri("/MainPage.xaml", UriKind. Relative));
            }
        }
        #endregion

        #region 增加/刷新 评论
        private void icon_AddComment_Click(object sender, EventArgs e)
        {
            this. NavigationService. Navigate(new Uri(string. Format("/View/AddComment.xaml?post={0}", postID), UriKind. Relative));
        }
        private void icon_RefreshComment_Click(object sender, EventArgs e)
        {
            this. comments. Reload(true, this. postID, 0, true);
        }
        #endregion

        #region 进入分享页面
        private void icon_SharePost_Click(object sender, EventArgs e)
        {
            switch ( this.pivot.SelectedIndex )
            {
                case 0:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. PostDetail;
                    break;
                case 1:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. Comments;
                    break;
                case 2:
                    DataSingleton. Instance. GoToSharePageType = GoToSharePageType. RelativePosts;
                    break;
            }
            this. NavigationService. Navigate(new Uri("/View/Share.xaml", UriKind. Relative));
        }
        #endregion

        #region 将文章订到桌面上
        private void menuItem_PinToStart_Click(object sender, EventArgs e)
        {
            if ( this.post != null )
            {
                Util. Tool. CreateShellTile(this. post);
            }
        }
        #endregion

        #region 在IE9中查看该文章
        private void menuItem_ViewInBrowser_Click(object sender, EventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask { Uri = new Uri(this. post. url, UriKind. Absolute) };
            task. Show( );
        }
        #endregion

        #region 处理PostID
        private void Receive_PostID( )
        {
            if ( this. NavigationContext. QueryString. ContainsKey("post") )
            {
                this. postID = this. NavigationContext. QueryString[ "post" ]. ToInt32( );
                this. comments. postID = postID;
                this. comments. Reload(true, postID);

                //加载数据
                this. Reload( );
            }
        }
        #endregion

        #region 处理页面入口模式
        private void Receive_Portal( )
        {
            if ( this.NavigationContext.QueryString.ContainsKey("portal") )
            {
                switch ( this.NavigationContext.QueryString["portal"] )
                {
                    case "PostDetail":
                        this. pivot. SelectedIndex = 0;
                        break;
                    case "Comments":
                        this. pivot. SelectedIndex = 1;
                        break;
                    case "RelativePosts":
                        this. pivot. SelectedIndex = 2;
                        break;
                }
            }
        }
        #endregion

        #region 进度条
        private void PostDetail_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray. ProgressIndicator = new ProgressIndicator( );
            SystemTray. ProgressIndicator. Text = "加载中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData. Source = this;
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
        }
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty. Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(PostDetail),
            new PropertyMetadata(false));

		public bool ProgressIndicatorIsVisible
		{
			get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
			set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
		}
        #endregion

        #region 登入注销处理
        //登入
        private void menuItem_Login_Click(object sender, EventArgs e)
        {
            Util. Tool. Login( );
        }

        //注销
        private void menuItem_Logout_Click(object sender, EventArgs e)
        {
            Util. Tool. Logout( );
            Util. Tool. CheckAppBar(this);
        }
        #endregion

		#region 浏览器滑动时删除作者，日期，评论数量
		private bool isDelete;
		private void browser_MouseMove(object sender, System. Windows. Input. MouseEventArgs e)
		{
			if ( isDelete == false )
			{
				this. Grid_Post. Children. Remove(this. Grid_Post. FindName("panel_author") as UIElement);
				TextBlock lbl_Title = this. Grid_Post. FindName("lbl_Title") as TextBlock;
				if ( lbl_Title != null )
				{
					lbl_Title. TextWrapping = TextWrapping. NoWrap;
					lbl_Title. HorizontalAlignment = System. Windows. HorizontalAlignment. Left;
				}
				isDelete = true;
			}
		}
		private void DisplayCommentCount( int count )
		{
			TextBlock lbl_CommentCount = this. pivot. FindName("pivotItemComment") as TextBlock;
			if ( lbl_CommentCount != null )
			{
				lbl_CommentCount. Text = string. Format("评论({0})", count. ToString( ));
			}
		}
		#endregion
	}
}